/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

class BSTIterator {
private:
    vector<TreeNode*> _v;   // 使用O(h)，保留二叉树的左子树.h为树的高度
public:
    void dfsLeft(TreeNode *root)
    {
        while(root)
        {
            _v.push_back(root);
            root = root->left;
        }
    }


    BSTIterator(TreeNode* root) {
        dfsLeft(root);
    }
    
    int next() {
        TreeNode *cur = _v.back();
        _v.pop_back();

        dfsLeft(cur->right);
        return cur->val;
    }
    
    bool hasNext() {
        return !_v.empty();
    }
};


/*
class BSTIterator {
private:
    TreeNode *_node;        // 当前节点
    stack<TreeNode*> _st;    // 存放访问的节点
public:
    BSTIterator(TreeNode* root) {
        _node = root;
    }
    
    int next() {
        while(_node)
        {
            _st.push(_node);
            _node = _node->left;
        }

        _node = _st.top();   // _node走到空，则说明左子树访问完了，此时访问根，根则是栈顶元素
        _st.pop();
        
        int val = _node->val;
        _node = _node->right; // 根访问完之后访问右子树

        return val;
    }
    
    bool hasNext() {
        // 栈不为空 || _node != nullptr 则说明还有下一个元素
        return (!_st.empty() || _node != nullptr);
    }
};
*/

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator* obj = new BSTIterator(root);
 * int param_1 = obj->next();
 * bool param_2 = obj->hasNext();
 */